﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace QD.Utils
{
    public class StringUtils
    {
     

        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        public static string GetEmailHostName(string strEmail)
        {
            if (strEmail.IndexOf("@") < 0)
                return null;
            return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower();
        }

        public static string RemoveHtml(string content)
        {
            if (string.IsNullOrEmpty(content))
                return string.Empty;
            return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
        }

        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }

        /// <summary>
        /// 替换\n(2016-9-18)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string ReplaceN(string data, string str)
        {
            if (str.Equals("\\r\\n"))
            {
                MatchEvaluator mr = delegate(Match m)
                {
                    return "\r\n";
                };
                str = Regex.Replace(str, @"\\r\\n", mr);
            }
            MatchEvaluator me = delegate(Match m) { return str; };
            data = Regex.Replace(data, @"&", me);
            return data;
        }

        /// <summary>
        /// 获取正则匹配值
        /// </summary>
        /// <param name="data"></param>
        /// <param name="pattern"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string GetRexData(string data, string pattern, int val)
        {
            MatchEvaluator me = delegate(Match m) { return @"\"; };
            pattern = Regex.Replace(pattern, @"\\", me);  
            //pattern = pattern.Replace(@'\\\\','\\');
            if (!string.IsNullOrEmpty(data))
            {
                Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
                if (re.IsMatch(pattern))
                {
                    return re.Match(data).Groups[val].Value;
                }
            }
            return string.Empty;
        }


        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }
 
        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name=”time”></param>
        /// <returns></returns>
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        /// <summary>
        /// 时间判断
        /// </summary>
        /// <param name="dt1"></param>
        /// <param name="dt2"></param>
        /// <returns></returns>
        public static bool IsDoWork(int startHour=8,int endHour=10)
        {
            return DateTime.Now.Hour >= startHour && DateTime.Now.Hour <= endHour;
        }
        /// <summary>
        /// 获取img
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static List<string> GetImgSrc(string content)
        {
            List<string> urlList = new List<string>();
            if (string.IsNullOrEmpty(content))
                return null;
            content = content.Replace("\n", "");
            string patt = @"<img(.*?)>";
            Regex reg = new Regex(patt, RegexOptions.IgnoreCase);
               string patt1 = "src=\"([\\s\\S]+?)\"";
                Regex reg1 = new Regex(patt1, RegexOptions.IgnoreCase);
            if (reg.IsMatch(content))
            {
                MatchCollection mc = reg.Matches(content);
                foreach (Match ma in mc)
                {
                   string url=reg1.Match(ma.Value).Groups[1].Value;
                   if (!string.IsNullOrEmpty(url))
                   {
                       urlList.Add(ConfigurationManager.AppSettings["proxyimg"]+url);
                   }
                } 
            }
            return urlList;
        }

        public static void ReplaceContentImg(string content)
        {

        }

        public static string JsonCharFilter(string sourceStr)
        {
            sourceStr = sourceStr.Replace("\\", "\\\\");
            sourceStr = sourceStr.Replace("\b", "\\b");
            sourceStr = sourceStr.Replace("\t", "\\t");
            sourceStr = sourceStr.Replace("\n", "\\n");
            sourceStr = sourceStr.Replace("\v", "\\v");
            sourceStr = sourceStr.Replace("\f", "\\f");
            sourceStr = sourceStr.Replace("\r", "\\r");
            return sourceStr.Replace("\"", "\\\"");
        }

        public static string GetUnicodeSubString(string str, int len, string tailString)
        {
            if (string.IsNullOrEmpty(str))
                return null;

            string result = string.Empty;
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);
            int charLen = str.Length;
            int byteCount = 0;
            int pos = 0;
            if (byteLen > len)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)
                        byteCount += 2;
                    else
                        byteCount += 1;
                    if (byteCount > len)
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == len)
                    {
                        pos = i + 1;
                        break;
                    }
                }

                if (pos >= 0)
                    result = str.Substring(0, pos) + tailString;
            }
            else
                result = str;

            return result;
        }

        public static bool ChkSql(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                string sql_1 = "exec|insert|delete|update|select|count|chr|mid|master|truncate|char|declare|proc|drop|create";
                string[] sql_c = sql_1.Split('|');
                foreach (string sl in sql_c)
                {
                    if (str.ToLower().IndexOf(sl) >= 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static string ChkSQL(string str)
        {
            return (str == null) ? "" : str.Replace("'", "''");
        }

        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            if (!string.IsNullOrEmpty(sHtmlText))
            {

                Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*? [\s\t\r\n]*>", RegexOptions.IgnoreCase);


                MatchCollection matches = regImg.Matches(sHtmlText);

                int i = 0;
                string[] sUrlList = new string[matches.Count];


                foreach (Match match in matches)
                    sUrlList[i++] = match.Groups["imgUrl"].Value;
                return sUrlList;
            }
            return null;
        }


        public static String ArrayToString(Array arr, String splitChar = ",", String format = "{0}")
        {
            if (arr == null) return String.Empty;
            StringBuilder sb = new StringBuilder();
            foreach (object item in arr)
            {
                sb.AppendFormat(format, item, arr);
                sb.Append(splitChar);
            }
            if (!String.IsNullOrEmpty(splitChar))
                if (sb.Length > 0) sb.Remove(sb.Length - splitChar.Length, splitChar.Length);
            return sb.ToString();
        }

        
        public static string[] SplitString(string strContent, string strSplit)
        {
            if (!string.IsNullOrEmpty(strContent))
            {
                if (strContent.IndexOf(strSplit) < 0)
                    return new string[] { strContent };

                return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
            }
            else
                return new string[0] { };
        }

        
        public static string[] SplitString(string strContent, string strSplit, int count)
        {
            string[] result = new string[count];
            string[] splited = SplitString(strContent, strSplit);

            for (int i = 0; i < count; i++)
            {
                if (i < splited.Length)
                    result[i] = splited[i];
                else
                    result[i] = string.Empty;
            }

            return result;
        }

        public static bool StartsWithIgnoreCase(string target, string lookfor)
        {
            if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(lookfor))
            {
                return false;
            }

            if (lookfor.Length > target.Length)
            {
                return false;
            }
            return (0 == string.Compare(target, 0, lookfor, 0, lookfor.Length, StringComparison.OrdinalIgnoreCase));
        }
    }
}
